package zh.demo.controller;

import com.alibaba.fastjson.JSONObject;
import org.codehaus.jackson.map.util.JSONPObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zh.demo.commons.Query;
import zh.demo.commons.R;
import zh.demo.commons.RRException;
import zh.demo.model.ArticleEntity;
import zh.demo.model.WechatArticleCollectEntity;
import zh.demo.service.ArticleService;
import zh.demo.service.WechatArticleCollectService;
import zh.demo.utils.IPUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author zhangheng
 * @email zh_123shmily@163.com
 * @date 2017-09-21 18:18:39
 */

@RestController
@RequestMapping(value = "/article")
public class ArticleController {

	private final Logger log = LoggerFactory.getLogger(ArticleController.class);
	@Autowired
	private ArticleService articleService;

	@Autowired
	private WechatArticleCollectService wechatArticleCollectService;

	public R selectArticleList(String type){

		return R.ok();
	}

	@RequestMapping(value = "/test11111",method = {RequestMethod.POST, RequestMethod.GET})
	public R testUrl(String text){
		System.out.println("i am in ..."+text);
		return R.ok().put("text",text);
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/articleList",method = RequestMethod.POST)
	public R list(HttpServletRequest request,String jsonstr){
		String orderType = request.getParameter("orderType");
		String status = request.getParameter("status");
		String page = request.getParameter("page");
		log.info("jsonStr-------------------:"+jsonstr);
		JSONObject m = JSONObject.parseObject(jsonstr);

//		JSONObject m = new JSONObject();
//		m.put("orderType",1);
		//查询列表数据
		//Query query = new Query(params);
		log.info("========================enter");
		Map<String, Object> params = new HashMap<>();
		//params.put("status",status);
		//log.info("#####################:"+m.get("orderType"));
		/*params.put("orderType",m.get("orderType"));
		params.put("status",m.get("status"));
		params.put("page",m.get("page"));*/
		params.put("orderType",orderType);
		params.put("status",status);
		params.put("page",page);
		List<Map<String, Object>> articleList = articleService.selectPublicArticleList(params);
		//List<ArticleEntity> articleList = articleService.queryList(params);
		//int total = articleService.queryTotal(params);
		
		//PageUtils pageUtil = new PageUtils(articleList, total, query.getLimit(), query.getPage());

		Map<String, Object> map = new HashMap<>();
		map.put("code",0);
		map.put("list",articleList);
		//map.put("total",total);
		return R.ok().put("list",articleList);
		//return R.ok().put("page", pageUtil);
	}

	@RequestMapping(value = "/selectArticleById",method = RequestMethod.POST)
	public R selectArticleById(Long id){
		Map<String, Object> res = articleService.selectArticleById(id);
		return R.ok().put("article",res);
	}


	/*`title` varchar(255) DEFAULT NULL COMMENT '标题',
			`tags` varchar(255) DEFAULT NULL COMMENT '标签',
			`type` varchar(50) DEFAULT NULL COMMENT '文章类型',
			`simple_content` varchar(255) DEFAULT NULL COMMENT '文章简介',
			`content` text COMMENT '文章内容',
			`thumb_image` varchar(255) DEFAULT NULL COMMENT '缩略图路径',
			`author` bigint(20) DEFAULT NULL COMMENT '作者',
			`create_time` datetime DEFAULT NULL COMMENT '发布时间',
			`publish_way` varchar(20) DEFAULT NULL COMMENT '发布途径',
			`ad_money` decimal(10,0) DEFAULT NULL COMMENT '广告费',
			`forward_money` decimal(10,0) DEFAULT NULL COMMENT '转发费',
			`forward_count` bigint(20) DEFAULT NULL COMMENT '转发数',
			`click_money` decimal(10,0) DEFAULT NULL COMMENT '点击金额',
			`click_count` bigint(20) DEFAULT NULL COMMENT '点击数',
			`left_ad_money` decimal(10,0) DEFAULT NULL COMMENT '剩余广告费',
			`modify_time` datetime DEFAULT NULL COMMENT '修改时间',
			`auditor` varchar(50) DEFAULT NULL COMMENT '审核人',
			`audit_time` datetime DEFAULT NULL COMMENT '审核时间',
			`status` varchar(20) DEFAULT NULL COMMENT '状态 1审核中 2未发布 3推广中 4已结束',
			`fail_reason` varchar(200) DEFAULT NULL COMMENT '失败原因',
			`forward_rule` varchar(20) DEFAULT NULL COMMENT '转发规则',
			`article_owner` varchar(20) DEFAULT NULL COMMENT '文章主体(企业/个人)',*/
	@RequestMapping(value = "/insertArticle",method = RequestMethod.POST)
	public Map<String, Object> insertArticle(String title, String tags, String type, String simple_content,
											 String thumb_image, Long author, Date create_time, String publish_way,
											 Double ad_money, Double forward_money, Long forward_count, Double click_money,
											 Long click_count, Double left_ad_money, String modify_time,
											 String auditor, String audit_time, String status, String fail_reason,
											 String forward_rule, String article_owner){//@RequestBody JSONObject jsonObjecttype
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 24HH:mm:ss");
		Calendar ca = Calendar.getInstance();
		ArticleEntity ac = new ArticleEntity();
		ac.setTitle(title);
		ac.setTags(tags);
		ac.setType(type);
		ac.setSimpleContent(simple_content);
		ac.setThumbImage(thumb_image);
		ac.setAuthor(author);
		ac.setCreateTime(create_time);
		ac.setPublishWay(publish_way);
		ac.setAdMoney(ad_money==null?null:new BigDecimal(ad_money));
		ac.setForwardMoney(forward_money==null?null:new BigDecimal(forward_money));
		ac.setForwardCount(forward_count);
		ac.setClickMoney(click_money==null?null:new BigDecimal(click_money));
		ac.setClickCount(click_count);
		ac.setLeftAdMoney(left_ad_money==null?null:new BigDecimal(left_ad_money));
		try {
			ac.setModifyTime(modify_time==null?null:format.parse(modify_time));
			ac.setAuditTime(audit_time==null?null:format.parse(audit_time));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		ac.setAuditor(auditor);
		ac.setStatus(status);
		ac.setForwardRule(forward_rule);
		ac.setArticleOwner(article_owner);

		Map<String, Object> res = articleService.save(ac);
		return res;
	}


	@RequestMapping(value = "/shareArticle",method = RequestMethod.POST)
	public Map<String, Object> shareArticle(Long articleId, String type, Long adId, Long userId,
											String ip, String province, String city, String district){
		Map<String, Object> res = articleService.shareArticle(articleId,type,adId,userId,ip,province,city,district);
		return res;
	}

	@RequestMapping(value = "/verifyArticle",method = RequestMethod.POST)
	public R verifyArticle(String articleId, String userId, String status){
		articleService.verifyArticle(articleId,userId,status);
		return R.ok();
	}
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	//@RequiresPermissions("generator:article:info")
	public Map<String, Object> info(@PathVariable("id") Long id){
		ArticleEntity article = articleService.queryObject(id);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code",0);
		map.put("article", article);
		return map;
		//return R.ok().put("article", article);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	//@RequiresPermissions("generator:article:save")
	public Map<String, Object> save(@RequestBody ArticleEntity article, String userId, JSONObject jsonObject){
		articleService.save(article);//article, userId,
				Map<String, Object> map = new HashMap<String, Object>();
		map.put("code",0);
		return map;
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	//@RequiresPermissions("generator:article:update")
	public Map<String, Object> update(@RequestBody ArticleEntity article){
		articleService.update(article);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code",0);
		return map;
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	//@RequiresPermissions("generator:article:delete")
	public Map<String, Object> delete(@RequestBody Long[] ids){
		articleService.deleteBatch(ids);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code",0);
		return map;
	}

	@Value("${byhd.imagesPath}")
	String path;

	@Value("${imageUrl}")
	String imageURL;

	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST, headers = {"Content-Type=multipart/form-data"})
	public Map<String, Object> test(@RequestBody MultipartFile file, HttpServletRequest request) {
		/*String url = request.getRequestURL().toString();
		String path = request.getContextPath();
		String spath = request.getServletPath();
		String address = request.getLocalAddr();*/
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<>();
		log.info("path======================"+path);
		String type="1";
		int port = request.getLocalPort();
		String ip = IPUtils.getLocalIp(request);
		String filePath = "";
		String filename = "";
		// 判断文件是否为空
		if (!file.isEmpty()) {
			if (file.getSize() > 10240000) {
				throw new RRException("上传失败：文件大小不能超过10M");
			}
			try {
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				/*String pixPath = null;
				if(type.equals("1")){
					pixPath = "/ID/";
				}else{
					pixPath = "/businessLicence";
				}*/
				// 文件保存路径
				filename = System.currentTimeMillis() + postfix;
				filePath = path + filename;
				File saveDir = new File(filePath);
				saveDir.setWritable(true,false);
				//判断目标文件所在的目录是否存在
				if (!saveDir.getParentFile().exists()) {
					//如果目标文件所在的目录不存在，则创建父目录
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
			} catch (Exception e) {
				e.printStackTrace();
				map.put("code",1);
				return map;
			}
		} else {
			throw new RRException("上传失败:请添加上传文件！");
		}
		log.info("filePath:" + filePath);

		map.put("url", imageURL+filename);
		map.put("code",0);
		return map;
	}




}
